
var CardUtil = (function (Utils) {
    var oldCard = ''
    return {
        readCardType: function (cardNo) {
            const cardType = {
                'suishenban': /^\d{28}$|https|^SHYB\d{26}$/,
                'weixin': /^\d{28}$/,
                'zhifubao': /^\d{28}$/,
                'shanghaixinpianka': /^\w{9}$/,
                'shanghaiyibaocitiaoka': /^\d{28}$/,
                'shenfenzheng': /^\d{18}$/
            }
        },
        huaxuRead: function (callback) {
            console.log('开始查询读卡信息')
            Utils.request('http://localhost:9100/?key=4006603260', 'get', null, function(error, data){
                console.log('查询读卡信息:', data)
                if (!error && data) {
                    if (!!callback) {
                        callback(data)
                    }
                } else {
                    console.error('【华旭】读卡失败，错误码：', error)
                }
            })
        },
        dzybRead: function (cardNo, callback) {
            Utils.request('http://localhost:8888/DzYbCodeQuery?qrcode=' + encodeURIComponent(cardNo), 'get', null, function(error, data){
                if (!error && data) {
                    if (!!callback) {
                        callback(eval(data))
                    }
                } else {
                    console.error('【华旭】读卡失败，错误码：', error)
                }
            })
        },
        selectPatientByCardNo: function (cardNo, callback) {
            Utils.request(Utils.baseUrl + '/patient/register/'+cardNo, 'get', null, function(error, data) {
                var response = {
                    code: 0,
                    message: '',
                    data: null
                }
                if (error) {
                    response = {
                        code: 0,
                        message: '',
                        data: null
                    }
                } else if (data && data.code === 200 && data.data.queue){
                    response.code = 1
                    response.message = 'success'
                    response.data = data.data
                }
                if (callback) {
                    callback(response)
                }
            })
        },
        readCardNo: function (cardNo, callback) {
            var response = {
                code: 0,
                message: '',
                data: null
            }
            oldCard = cardNo

            //this.huaxuRead
            // 如果是28位数字，先默认是白玉兰卡，取前十位查询患者数据， 有可能该卡确实是电子医保卡但是取到前10位的数字查询到的患者是白玉兰卡
            if (/^\d{28}$/.test(cardNo)) {
                cardNo = cardNo.substring(0, 10)
                console.log("卡号匹配前十位:", cardNo)
                CardUtil.selectPatientByCardNo(cardNo, function (res) {
                    console.log("卡号匹配前十位查询结果:", res)
                    if (res.code) {
                        response = {
                            code: 1,
                            message: 'success',
                            data: res.data
                        }
                        if (callback) callback(res)
                    } else {
                        console.log("卡号匹配前全部:", oldCard)
                        CardUtil.selectPatientByCardNo(oldCard, function (res) {
                            console.log("卡号匹配全部查询结果:", res)
                            if (res.code) {
                                response = {
                                    code: 1,
                                    message: 'success',
                                    data: res.data
                                }
                                if (callback) callback(res)
                            } else {
                                console.log("卡号匹配电子医保卡")
                                // 查询电子医保卡
                                CardUtil.dzybRead(oldCard, function(data) {
                                    console.log("卡号匹配电子医保卡查询结果:", data)
                                    if (data && data.length) {
                                        var dzybRes = data[0]
                                        if ( dzybRes.msg && /[a-zA-Z0-9]+/.test(dzybRes.msg)) {
                                            cardNo = dzybRes.msg
                                            console.log("卡号匹配电子医保卡查询卡号:", cardNo)
                                            CardUtil.selectPatientByCardNo(cardNo, function(res) {
                                                console.log("卡号匹配电子医保卡查询患者:", res)
                                                if (res.code) {
                                                    response = {
                                                        code: 1,
                                                        message: 'success',
                                                        data: res.data
                                                    }
                                                }
                                                if (callback) callback(response)
                                            })
                                        } else {
                                            response = {
                                                code: 0,
                                                message: dzybRes.msg,
                                                data: null
                                            }
                                            if (callback) callback(response)
                                        }
                                    } else {
                                        response = {
                                            code: 0,
                                            message: '医保卡查询失败，请重试',
                                            data: null
                                        }
                                        if (callback) callback(response)
                                    }
                                })
                            }
                        })
                    }
                })
            } else if (/^\d{28}$|https|^SHYB\d{26}$/.test(oldCard)) {
                console.log("卡号匹配电子医保卡查询结果:", oldCard)
                // 读取电子医保卡
                CardUtil.dzybRead(oldCard, function(data) {
                    console.log("卡号匹配电子医保卡查询结果:", data)
                    if (data && data.length) {
                        var dzybRes = data[0]
                        if ( dzybRes.msg && /[a-zA-Z0-9]+/.test(dzybRes.msg)) {
                            cardNo = dzybRes.msg
                            console.log("卡号匹配电子医保卡查询卡号:", cardNo)
                            CardUtil.selectPatientByCardNo(cardNo, function(res) {
                                console.log("卡号匹配电子医保卡查询患者:", res)
                                if (res.code) {
                                    response = {
                                        code: 1,
                                        message: 'success',
                                        data: res.data
                                    }
                                }
                                if (callback) callback(response)
                            })
                        } else {
                            response = {
                                code: 0,
                                message: dzybRes.msg,
                                data: null
                            }
                            if (callback) callback(response)
                        }
                    } else {
                        response = {
                            code: 0,
                            message: '医保卡查询失败，请重试',
                            data: null
                        }
                        if (callback) callback(response)
                    }
                })
            }  else {
                console.log("卡号直接查询患者:", oldCard)
                CardUtil.selectPatientByCardNo(oldCard, function (res) {
                    console.log("卡号直接查询患者结果:", res)
                    if (callback) callback(res)
                })
            }
        }
    }
})(Utils)

const Dialog = (function (Utils) {

    var _colors = ['#00939c', '#019d76', '#f1604b', '#2d4f8f', '#ef9e24']

    var _cardNo = ''

    var _closeDialogInterval

    var _requestSending = false

    var _isShow = false

    var _queueInfo = null

    var _openInterval = 60

    var _generateDoctorHtml = function (doctors, queue) {
        var doctorContainer = document.createElement("div");
        doctorContainer.setAttribute("class", "yy-screen-dialog_body-doctor")
        var template = document.querySelector("#html-template-container .yy-screen-dialog_body-doctor-item");
        for (var i = 0; i<doctors.length; i++) {
            var doctor = doctors[i]
            var bgColor = _colors[i % _colors.length]
            var doctorItem = document.createElement("div")
            doctorItem.setAttribute("class", template.getAttribute("class"))
            doctorItem.innerHTML = template.innerHTML
            if (queue.doctorId && queue.doctorId === doctor.id) {
                doctorItem.setAttribute("class", doctorItem.getAttribute("class") + " yy-screen-dialog_body-doctor-item--active")
            }
            doctorItem.querySelector("div:first-child").setAttribute("style", `background-color:${bgColor};`)
            doctorItem.querySelector("div:first-child").setAttribute("data-doctor-id", doctor.id)
            if (doctor.photo) {
                doctorItem.querySelector('div.yy-screen-dialog_body-doctor-item-photo > img')
                    .setAttribute("src", "http://192.168.31.192/dev-api" + doctor.photo)
            }

            doctorItem.querySelector('div.yy-screen-dialog_body-doctor-item-info > div:nth-child(1)').innerText = doctor.name
            doctorItem.querySelector('div.yy-screen-dialog_body-doctor-item-info > div:nth-child(2)').innerText = doctor.levelName || ''
            doctorContainer.append(doctorItem)
        }
        document.querySelector("div.yy-screen-dialog_body > div").append(doctorContainer)

        if (!_queueInfo.queue.state) {
            var allDoctorItem = doctorContainer.querySelectorAll('div.yy-screen-dialog_body-doctor-item')
            for (var item of allDoctorItem) {
                item.addEventListener('click', Dialog.selectDoctor)
            }
        }
    }
    var _generatePatientHtml = function (queue, await) {

        var template = document.querySelector("#html-template-container .yy-screen-dialog_body-patient");
        var patient = document.createElement("div")
        patient.setAttribute("class", template.getAttribute("class"))
        patient.innerHTML = template.innerHTML
        patient.querySelector("div:nth-child(1) > span:nth-child(2)").innerText = queue.patientName;
        patient.querySelector("div:nth-child(2) > span:nth-child(2)").innerText = queue.registerNo;
        patient.querySelector("div:nth-child(3) > span:nth-child(2)").innerText = Utils.formatDate(queue.registerTime).substring(11);
        patient.querySelector("div:nth-child(4) > span:nth-child(2)").innerText = queue.departName;
        if (queue.doctorName) {
            patient.querySelector("div:nth-child(5) > span:nth-child(2)").innerText = queue.doctorName;
        } else {
            patient.querySelector("div:nth-child(5)").style.display = 'none';
        }
        patient.querySelector("div:nth-child(6) > span:nth-child(2)").innerText = await;
         document.querySelector("div.yy-screen-dialog_body > div").append(patient)
    }


    // 根据卡号查询患者挂号信息
    var _loadRemoteData = function (cardNo, callback) {
        Dialog.addLoading()
        Utils.request(Utils.baseUrl + '/patient/register/'+cardNo, 'get', null, function(error, data) {
            Dialog.removeLoading()
            if (!error && data && data.code === 200 && data.data.queue) {
                var result = data.data
                _queueInfo = result
                _generatePatientHtml(result.queue, result.await)
                if (!result.queue.state) {
                    document.querySelector("div.yy-screen-dialog").setAttribute("class", "yy-screen-dialog")
                } else {
                    var body = document.querySelector("div.yy-screen-dialog_body")
                    body.querySelector("div.yy-screen-dialog_body-message").innerHTML = `<span>已完成签到，请耐心等待叫号！</span>`
                }
            } else {
              Dialog.addNoData()
            }
        })
    }

    var _signByCardNo = function (cardNo) {
        _requestSending = true
        document.querySelector("div.yy-screen-dialog_footer > button").innerText = "正在处理..."
        var params = null
        var doctorId =  Dialog.getSelectDoctor()

        if (doctorId) {
            params = {
                itemId: _queueInfo.queue.itemId,
                categoryId: _queueInfo.queue.categoryId,
                doctorId: doctorId
            }
        }
        Utils.request(Utils.baseUrl + '/patient/sign/'+cardNo, 'POST', JSON.stringify(params), function(error, data) {
            var body = document.querySelector("div.yy-screen-dialog_body")
            var patient = body.querySelector("div.yy-screen-dialog_body-message")
            if (!error && data && data.code === 200) {
                document.querySelector("div.yy-screen-dialog").setAttribute("class", "yy-screen-dialog hide-sign-button")
                body.querySelector(":first-child").innerHTML = `<span style="font-size: 0.5rem;">签到成功</span>`
            } else {
                patient.innerHTML = `<span>签到失败，请至护士台处理！</span>`
                setTimeout(function() {
                    patient.innerHTML = ''
                }, 3000)
            }
            _requestSending = false
            document.querySelector("div.yy-screen-dialog_footer > button").innerText = "签到"
        })
    }

    return {
        getSelectDoctor: function () {
            var activeItem = document.querySelector("div.yy-screen-dialog_body > div  .yy-screen-dialog_body-doctor-item--active")
            if (activeItem) {
                return activeItem.querySelector(":first-child").dataset.doctorId
            }
            return null
        },
        addNoData: function (message) {
            var body = document.querySelector("div.yy-screen-dialog_body > div")
            var interval = 5
            body.innerHTML = `<div style="font-size: 0.5rem; display: flex;flex: 1;align-items: center;flex-direction: column; justify-content: center;">
                                        <div>${message ? message : '查询挂号信息失败，请至护士台处理。'}</div>
                                    </div>`
        },
        selectDoctor: function () {
            if (this.getAttribute('class') && this.getAttribute('class').includes('yy-screen-dialog_body-doctor-item--active')) {
                this.setAttribute("class", "yy-screen-dialog_body-doctor-item")
            } else {
                var activeItem = document.querySelector('div.yy-screen-dialog_body-doctor  div.yy-screen-dialog_body-doctor-item--active')
                if (activeItem) {
                    activeItem.setAttribute("class", "yy-screen-dialog_body-doctor-item")
                }
                this.setAttribute("class", this.getAttribute('class') + ' yy-screen-dialog_body-doctor-item--active')
            }
        },
        addLoading: function () {
            var loadingEle = document.querySelector("#sign_dialog div.yy-screen-dialog_loading")
            if (!loadingEle) {
                var body = document.querySelector("div.yy-screen-dialog_body > div")
                body.innerHTML = `<div class="yy-screen-dialog_loading"><span>正在查询，请稍后...</span></div>`
            }
        },
        removeLoading: function () {
            var loadingEle = document.querySelector("#sign_dialog div.yy-screen-dialog_loading")
            if (loadingEle) {
                loadingEle.remove()
            }
        },
        showCloseIntervel: function () {
            document.querySelector("#sign_dialog .yy-screen-dialog_header .yy-screen-dialog_header-right-time").innerHTML =  `<span style="color: #66b1ff;">${_openInterval}</span>秒后将自动关闭`
            _closeDialogInterval = setInterval(function() {
                _openInterval -= 1
                if (_openInterval === 0) {
                    if (_closeDialogInterval) {
                        clearInterval(_closeDialogInterval)
                        _closeDialogInterval = null
                    }
                    _openInterval = 60
                    Dialog.close()
                    return
                }
                document.querySelector("#sign_dialog .yy-screen-dialog_header .yy-screen-dialog_header-right-time").innerHTML = `<span style="color: #66b1ff;">${_openInterval}</span>秒后将自动关闭`
            }, 1000)
        },
        show: function (cardNo) {
            if (_closeDialogInterval) {
                clearInterval(_closeDialogInterval)
                _closeDialogInterval = null
            }
            document.querySelector("#sign_dialog .yy-screen-dialog_header-close").addEventListener('click', Dialog.close)
            document.querySelector("div#sign_dialog").style.display = 'block';
            Dialog.showCloseIntervel()
            _cardNo = cardNo
            Dialog.addLoading()
            CardUtil.readCardNo(Utils.findMaxRepeatedSubstring(_cardNo), function (res) {
                console.log('卡号读取患者信息:::', res);
                Dialog.removeLoading()
                if (res.code) {
                    var result = res.data
                    _queueInfo = result
                    _generatePatientHtml(result.queue, result.await)
                    //_generateDoctorHtml(result.employees, result.queue)
                    console.log('current query patient data:::', result);
                    if (!result.queue.state || (result.queue.state === 2 && result.queue.visitState > 2) || result.queue.state === 5) {
                        document.querySelector("div.yy-screen-dialog").setAttribute("class", "yy-screen-dialog")
                    } else if (result.queue.state && result.queue.state === 3) {
                        var body = document.querySelector("div.yy-screen-dialog_body")
                        body.querySelector("div.yy-screen-dialog_body-message").innerHTML = `<span>你已过号，请重新签到！</span>`
                        document.querySelector("div.yy-screen-dialog").setAttribute("class", "yy-screen-dialog")
                    }else {
                        var body = document.querySelector("div.yy-screen-dialog_body")
                        body.querySelector("div.yy-screen-dialog_body-message").innerHTML = `<span>已完成签到，请耐心等待叫号！</span>`
                    }
                } else {
                    Dialog.addNoData(res.message)
                }

            })

            return this
        },
        close: function () {
            _queueInfo = null
            if (_closeDialogInterval) {
                clearInterval(_closeDialogInterval)
                _closeDialogInterval = null
            }
            _openInterval = 60
            var allDoctorItem = document.querySelector("div.yy-screen-dialog").querySelectorAll('div.yy-screen-dialog_body-doctor-item')
            for (var item of allDoctorItem) {
                item.removeEventListener('click', Dialog.selectDoctor)
            }
            var body = document.querySelector("div.yy-screen-dialog_body")
            body.querySelector("div.yy-screen-dialog_body-message").innerHTML = ``
            document.querySelector("div.yy-screen-dialog").setAttribute("class", "yy-screen-dialog hide-sign-button")
            document.querySelector("#sign_dialog .yy-screen-dialog_header-close").removeEventListener('click', Dialog.close)
            document.querySelector("div#sign_dialog").style.display = 'none';
        },
        isShow: function () {
            return document.querySelector("div#sign_dialog").style.display != 'none'
        },
        onSign: function () {
            if (_cardNo && !_requestSending) {
                _signByCardNo(_cardNo)
            }
        }
    }
})(Utils)

window.onload = function () {
    var params = Utils.getQueryParams(window.location.href)
    // debugger
    if (params && params.server_url) {
        Utils.baseUrl = params.server_url
    }
    DateTimeRender.render(document.querySelector("div.yy-screen-header_time"))
    document.querySelector("input.yy-screen-content_card-input-input").focus()
    document.body.addEventListener('click', function() {
        document.querySelector("input.yy-screen-content_card-input-input").focus()
    })
    document.querySelector("div.yy-screen-content_card-input-button > button").addEventListener('click', function (event) {
        CardUtil.huaxuRead(function(res) {
            var _cardNo = res.CardNo || res.cardNo
            console.log('查询读卡卡号:', _cardNo)
            if (_cardNo && !Dialog.isShow()) {
                Dialog.show(_cardNo)
            }
            document.querySelector("input.yy-screen-content_card-input-input").value = ""
        })
    })
    Utils.resetFontSize()
    window.onresize = function () {
        Utils.resetFontSize()
    }
    var inputTimeout = null;
    document.querySelector("input.yy-screen-content_card-input-input").addEventListener('input', function (event) {
        var that = this
        if (inputTimeout) {
            clearTimeout(inputTimeout)
            inputTimeout = null;
        }
        inputTimeout = setTimeout(function () {
            var cardNo = Utils.findMaxRepeatedSubstring(that.value)
            if (cardNo && !Dialog.isShow()) {
                Dialog.show(cardNo)
            }
            document.querySelector("input.yy-screen-content_card-input-input").value = ""
        }, 1500)
    })
    document.querySelector("input.yy-screen-content_card-input-input").addEventListener('blur', function(){
        document.querySelector("input.yy-screen-content_card-input-input").focus()
    })

    document.querySelector("div.yy-screen-dialog_footer  > button").addEventListener('click', function () {
        Dialog.onSign()
    })
}